<template>
  <div>
    <div style="display: flex;justify-content: space-between; width: 100%">
      <el-form
        :model="formData"
        label-position="left"
        label-width="100px"
        :rules="ruleForm"
        ref="ruleForm"

      >
        <el-form-item label="商户名称" prop="name">
          <el-input v-model="formData.name" type="text" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="商户地址" prop="address">
          <el-input v-model="formData.address" type="text" placeholder="请输入地址" />
        </el-form-item>
        <div style="display: flex">
          <el-form-item label="营业时间"></el-form-item>
          <el-form-item label="非周末" prop="start_time"  label-width="70px">
            <el-time-picker
              is-range
              v-model="formData.start_time"
              range-separator="至"
              format="HH:mm"
              value-format="timestamp"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围">
            </el-time-picker>
          </el-form-item>
          <el-form-item label="周末" prop="end_time" label-width="50px" style="margin-left: 80px">
            <el-time-picker
              is-range
              v-model="formData.end_time"
              range-separator="至"
              format="HH:mm"
              value-format="timestamp"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围">
            </el-time-picker>
          </el-form-item>
        </div>
        <el-form-item label="联系电话" prop="tel">
          <el-input v-model="formData.tel" type="text" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="商户经度" prop="lon">
          <el-input v-model="formData.lon" style="width: 200px;margin-right: 12px"
                    oninput="value=value.replace(/[^\d^\.]+/g,'')"
                    @blur="blurLngAddLat"
                    @input="inputLngAddLat"
                    type="number" placeholder="请输入商户经度" />
        </el-form-item>
        <el-form-item label="商户纬度" prop="lat">
          <el-input v-model="formData.lat" style="width: 200px"
                    oninput="value=value.replace(/[^\d^\.]+/g,'')"
                    @blur="blurLngAddLat"
                    @input="inputLngAddLat"
                    type="number" placeholder="请输入商户纬度" />
          <span style="color:#97a8be;">
            提示：删除任意经纬度可以重新选点
          </span>
          <div class="amap-wrapper">
            <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"
            ></el-amap-search-box>
            <el-amap vid="amap" :zoom="zoom" :center="center" class="amap-demo" :events="events">
              <el-amap-marker v-for="(marker, index) in markers" :vid="index"
                              :position="marker.position" :events="marker.events"
                              animation="AMAP_ANIMATION_DROP"
              ></el-amap-marker>
            </el-amap>
          </div>
        </el-form-item>
        <el-form-item label="商户轮播" prop="imgs_json">
          <el-upload
            class="up-load"
            :class="formData.imgs_json && formData.imgs_json.length > 9 ? 'hidden':''"
            multiple
            action="https://up.qiniup.com"
            :limit="10"
            :data="uploadData"
            accept="image/*"
            :file-list="formData.imgs_json"
            list-type="picture-card"
            :before-upload="beforeAvatarUpload"
            :on-success="upSuccess"
            :on-exceed="overMax"
            :on-remove="handleRemove"
          >
            <i slot="default" class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
    <div style="margin: 5% 0 0 5%;">
      <el-button plain style="margin-right: 3%;" @click="$emit('close')">取消</el-button>
      <el-button type="primary" @click="handleChangeStudentInfo">保存</el-button>
    </div>
  </div>
</template>

<script>
import TableMixins from '@/components/WxTables/mixins'
import Tinymce from '@/components/Tinymce/Tinymce'

var validPhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入电话号码'))
  } else if (!/^1[3|4|5|7|8][0-9]\d{8}$/.test(value)) {
    callback(new Error('请输入正确的11位手机号码'))
  } else {
    callback()
  }
}
export default {
  name: 'MerchantInfo',
  components: {
    Tinymce
  },
  mixins: [TableMixins],
  props: {
    formData: {
      type: Object
    }
  },
  created(){
    this.firstLoad = false
    this.blurLngAddLat()
  },
  data() {
    return {
      inputVisible: false,
      inputValue: '',
      qiNiuToken: '',
      ruleForm: {
        name: [
          { required: true, message: '请填写商户名称', trigger: 'blur' }
        ],
        tel: [
          { required: true, trigger: 'blur', validator: validPhone }
        ],
        address: [
          { required: true, message: '请填写商户地址', trigger: 'blur' }
        ],
        start_time: [
          { required: true, message: '请选择营业时间', trigger: 'blur' }
        ],
        end_time: [
          { required: true, message: '请选择营业时间', trigger: 'blur' }
        ],
        lon: [
          { required: true, message: '请输入商户经度', trigger: 'blur' }
        ],
        lat: [
          { required: true, message: '请输入商户纬度', trigger: 'blur' }
        ],
        imgs_json: [
          { required: true, message: '请上传图片', trigger: 'blur' }
        ],
      },
      parentIndex: 0,
      editIsAdd: '',
      isType: '',
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      addParentsList: {
        relationship: '',
        name: '',
        tel_num: '',
        img: ''
      },
      imageUrl: '',
      parentsIndex: 0,
      editJanitor: false,
      select_dept: [],

      //地图参数
      zoom: 11,
      center: [121.006725,29.144079],
      markers: [],
      searchOption: {
        city: '天台县',
        citylimit: false
      },
      events: {
        click: (e) => {
          const item_obj = {
            position: [e.lnglat.lng, e.lnglat.lat]
          }
          if(this.markers.length < 1) {
            this.$set(this.formData,'lon',e.lnglat.lng)
            this.$set(this.formData,'lat',e.lnglat.lat)
            this.markers.push(item_obj)
          }
        }
      }
    }
  },
  methods: {
    /**
     * 搜索地图点位
     * @param pois
     */
    onSearchResult(pois) {
      let latSum = 0
      let lngSum = 0
      if (pois.length > 0) {
        pois.forEach(poi => {
          let { lng, lat } = poi
          lngSum += lng
          latSum += lat
        })
        let center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        }
        this.center = [center.lng, center.lat]
      }
    },
    /**
     * 值改变关闭点位
     */
    inputLngAddLat() {
      this.markers = []
    },
    /**
     * 失焦重新计算点位
     */
    blurLngAddLat() {
      if(this.formData.lon && this.formData.lat && !this.markers.length) {
        const item = {
          position: [this.formData.lon, this.formData.lat]
        }
        this.markers.push(item)
      }
    },
    /**
     * 监控上传数量
     */
    overMax() {
      this.$message.warning({ message: '上传图片最大为10张' })
    },
    /**
     * 得到上传成功的文件
     * @param fileList
     * @param type
     */
    getFile(fileList,type) {
      this.$set(this.formData,'imgs_json',fileList)
    },
    /**
     * 删除图片
     * @param fileList
     */
    deleteFile(fileList) {
      this.$set(this.formData,'imgs_json',fileList)
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleIsAdd(type, index) {
      this.editIsAdd = type
      this.parentIndex = index
      if (type === 'create') {
        this.isType = '添加'
        this.addParentsList = {}
      }
      if (type === 'edit') {
        this.isType = '编辑'
        this.addParentsList = JSON.parse(JSON.stringify(this.formData.parents[index]))
      }
      this.editJanitor = true
    },
    beforeAddAvatarUpload(file) {
      uploadNormalFile(file, (res) => {
        this.$set(this.addParentsList, 'img', res)
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    /**
     * 保存
     */
    handleChangeStudentInfo() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let list = JSON.parse(JSON.stringify(this.formData));
          if(this.formData.imgs_json && this.formData.imgs_json.length){
            list.imgs_json = this.formData.imgs_json.map(item => {
              return item.name ? this.img_url + item.response.key : this.img_url + item.uid
            })
          }
          for (let i in list){
            if(['start_time'].includes(i)){
              list.work_day_start = this.$dayjs(list[i][0]).format('HH:mm')
              list.work_day_end = this.$dayjs(list[i][1]).format('HH:mm')
            }
            if(['end_time'].includes(i)){
              list.rest_day_start = this.$dayjs(list[i][0]).format('HH:mm')
              list.rest_day_end = this.$dayjs(list[i][1]).format('HH:mm')
            }
          }
          for (let i in list){
            if(['start_time','end_time'].includes(i)){
              delete list[i]
            }
          }
          this.$emit('saveFrom',list)
        } else {
          return false;
        }
      });
    },
  }
}
</script>
<style scoped>
.amap-wrapper {
  position: relative;
  height: 24rem;
  margin-top: 8px;
}

.amap-demo {
  height: 100%;
}

.search-box {
  position: absolute;
  top: 4px;
  left: 4px;
}

.amap-page-container {
  position: relative;
}

.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.time_title{
  font-size: 14px;
  color: #606266;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.hidden >>> .el-upload--picture-card {
  display: none;
}
</style>
<style lang="scss" src="./style/Form.scss" scoped>

</style>
